from django.shortcuts import render

# Create your views here.
from collection_manage.models import UserCollection
from ad_manage.models import Advertisement
import base64
from django.http import HttpResponse, JsonResponse
import json
from django.forms.models import model_to_dict
from django.db.models import Q
import operator
from sqlalchemy.util import reduce
from django.views.decorators.csrf import csrf_exempt
from collection_manage.controller import collect_controller
@csrf_exempt
def collect(request):
    advertisement_id = int(request.POST.get('id').replace('\n',''))
    token = request.COOKIES.get('tooken', '')
    if token != ""  and token != "null":
        tooken = request.COOKIES.get('tooken')
        payload = tooken.split(".")[1] + "=="
        a = base64.b64decode(payload).decode('unicode_escape')
        user_info = json.loads(a)
        user_id = user_info.get("user_id")
        result = collect_controller(user_id,advertisement_id)

        return JsonResponse({'json_data': result})

    else:
        return render(request, 'html/main/error.html', None)

@csrf_exempt
def collection(request):
    return render(request, 'html/main/index_collect.html', None)

@csrf_exempt
def user_collection(request):
    user_id = request.GET.get('id')
    if user_id!=None:
        userCollection = UserCollection.objects.filter(user_id=user_id).values("advertisement_id")
        ad_id_arr = []
        if userCollection.count()!=0:
            for c in userCollection:
                ad_id_arr.append(c.get('advertisement_id'))

            advertisement = Advertisement.objects.filter(
                reduce(operator.or_, map(lambda x: Q(id__contains=x), ad_id_arr)))
            print(advertisement.count())
            a = {'json_data': [model_to_dict(item) for item in advertisement]}

            return JsonResponse({'json_data': [model_to_dict(item) for item in advertisement]})
        else:
            return JsonResponse({'message':"null collection"})

@csrf_exempt
def is_collect(request):
    user_id = int(request.GET.get('user_id'))
    ad_id = int(request.GET.get('ad_id'))
    userCollection = UserCollection.objects.filter(user_id=user_id).filter(advertisement_id=ad_id)
    if(len(userCollection)>0):
        return JsonResponse({'json_data':'is_collected'})
    else:
        return JsonResponse({'json_data':'not_collected'})
